package br.com.timecardforpeon.sqlite.domain;

import static br.com.timecardforpeon.domain.Entry.LIST_BY_DAY_QUERY;
import static br.com.timecardforpeon.domain.Entry.LIST_BY_PERIOD_QUERY;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import br.com.timecardforpeon.domain.Day;
import br.com.timecardforpeon.domain.Entry;
import br.com.timecardforpeon.sqlite.BasicDao;
import br.com.timecardforpeon.util.Util;

public class EntryDao extends BasicDao<Entry> {

	public EntryDao(Context context) {
		super(context);
	}

	public List<Entry> listByDay(Date day) {
		
		try {
		
			return this.execute(LIST_BY_DAY_QUERY, Util.dateToString(day));
		}
		catch (Exception e) {
			Log.e("timeCard4Peon", "Exception listByDay", e);
		}
		
		return new ArrayList<Entry>();
	}
	
	public List<Entry> listByPeriod(Date from, Date to) {
		
		try {
			
			return this.execute(LIST_BY_PERIOD_QUERY, Util.dateToString(from), Util.dateToString(to));
		}
		catch (Exception e) {
			Log.e("timeCard4Peon", "Exception listByDay", e);
		}
		
		return new ArrayList<Entry>();
	}
	
	@Override
	public Entry cursorToDomain(Cursor cursor) throws Exception {

		Entry entry = new Entry();
		entry.setId(cursor.getLong(0));
		entry.setCheckIn(Util.stringToDateTime(cursor.getString(1)));
		String checkOut = cursor.getString(2);
		if (checkOut != null && !checkOut.equals("")) {
			entry.setCheckOut(Util.stringToDateTime(checkOut));
		}
		
		// Está trazendo o objeto Day
		if (cursor.getColumnCount() > 4) {
			
			Day day = new Day();
			day.setId(cursor.getLong(4));
			day.setDay(Util.stringToDate(cursor.getString(5)));
			day.setNotes(cursor.getString(6));
			entry.setDay(day);
		}

		return entry;
	}
}